package py.com.erpone.util;




import java.io.Serializable;
import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.inject.Named;

/**
 *
 * @author curso
 */
@Named(value = "localeSelector")
@SessionScoped
public class LocaleSelector implements Serializable{
    
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Locale locale;    
    private ResourceBundle mensajes;
    private static Map<String,String> countries;
    private String localeCode = "es"; //default value 
    
    static{
	countries = new LinkedHashMap<String,String>();
	countries.put("United Kingdom", "en"); //label, value
	countries.put("Espanol", "es");
    }
    
    public LocaleSelector(){        
        try {
            locale= FacesContext.getCurrentInstance().getViewRoot().getLocale();
            mensajes=ResourceBundle.getBundle("mensaje", locale);
        } catch (Exception e) {
            e.printStackTrace();
        }        
    }

    
    public Locale getLocale() {        
        //System.out.println("getLocale: "+locale.getLanguage());
        //System.out.println("getLocale: "+localeCode);
        return locale;
    }

    public void setLocale(Locale locale) {
        System.out.println("setLocale: "+locale.getLanguage());
        try {
            this.locale = locale;    
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        
    }

    public ResourceBundle getMensajes() {
        return mensajes;
    }

    public void setMensajes(ResourceBundle mensajes) {
        this.mensajes = mensajes;
    }
        
    public String getMensaje(String key, Object... params) {
        return MessageFormat.format(mensajes.getString(key), params);
    }
    
    public void setIdioma(String idioma){        
        if (idioma.indexOf("-") > -1)
            locale = new Locale(idioma.substring(0, idioma.indexOf("-")),
            idioma.substring(idioma.indexOf("-") + 1));
	else
            locale = new Locale(idioma);
        mensajes=ResourceBundle.getBundle("mensaje", locale);
        FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
    }
    

    public void countryLocaleCodeChanged(ValueChangeEvent e){
        System.out.println("valueChangeEvent");
	//assign new value to localeCode
	setIdioma(e.getNewValue().toString());
        localeCode = e.getNewValue().toString();
    }
    
    public Map<String,String> getCountryInMap() {
		return LocaleSelector.countries;
    }
    
    public String getLocaleCode() {
		return localeCode;
	}
 
	public void setLocaleCode(String localeCode) {
		this.localeCode = localeCode;
	}
        
        
}
